package handler

import (
	"ebip/internel/errs"
	"ebip/internel/ioc"
	"ebip/internel/service"
	"ebip/internel/types"
	"ebip/internel/web/middlewares/jwtx"
	"ebip/pkg/ginl/wrap_gin"
	"errors"
	"github.com/gin-gonic/gin"
)

// @Description
// @Author 代码小学生王木木

type AuthHandler struct {
	capSvc  service.ICaptchaSvc
	authSvc service.IAuthSvc
	types.Res
	jwtx.JwtHandler
}

func NewAuthHandler(capSvc service.ICaptchaSvc, authSvc service.IAuthSvc, j jwtx.JwtHandler) *AuthHandler {
	return &AuthHandler{
		capSvc:     capSvc,
		authSvc:    authSvc,
		JwtHandler: j,
		Res:        types.Res{},
	}
}

func (h *AuthHandler) PwdLogin(ctx *gin.Context, req types.PwdLoginReq) (wrap_gin.Result, error) {
	// 测试环境不校验图片验证码
	if ioc.AppConfig.ServiceEnv != "dev" {
		check := h.capSvc.CheckCaptcha(req.CaptchaId, req.CaptchaCode, false)
		if !check {
			return h.ErrX(errs.ImgCheckError), errors.New("验证码错误")
		}
	}
	user, err := h.authSvc.PwdLogin(ctx, req.UserName, req.Password)
	if err != nil {
		return h.ErrX(errs.AuthLoginFailed), err
	}
	// 组装token
	token, err := h.GetJWTToken(ctx, user.ID)
	if err != nil {
		return h.ErrX(errs.AuthTokenGenFailed), err
	}
	return h.SuccesJson(token), nil
}

func (h *AuthHandler) LogoutUser(ctx *gin.Context, user types.UserClaims) (wrap_gin.Result, error) {
	// TODO 要退出相关事宜
	return h.SuccesJson("success"), nil
}
